package com.example.mygrade.service.impl;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.example.mygrade.domain.Course;
import com.example.mygrade.domain.SC;
import com.example.mygrade.domain.Student;
import com.example.mygrade.repository.SCRepository;
import com.example.mygrade.service.SCService;
import com.example.mygrade.vo.Import;
import com.example.mygrade.vo.importSC;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

@Service
public class SCImplService implements SCService {
    @Autowired
    private SCRepository scRepository;

    public List<SC> findAll(){
        return scRepository.findAll();
    }
    /**
     * 只做分页的查询
     * @param pageable
     * @return
     */
    public Page<SC> findAll(Pageable pageable){
        return scRepository.findAll(pageable);
    }

    public Page<SC> findAll(Example<SC> student, Pageable pageable){
        return scRepository.findAll(student,pageable);
    }

    /**
     * 按id进行查询
     * @param id 主键，整数
     * @return
     */
    public SC findById(Integer id){

        SC sc =scRepository.findById(id).orElse(null);
        return sc;
    }

    public List<SC> findBySno(String sno){
        return scRepository.findBySno(sno);
    }
    public List<SC> findByCname(String cname){
        return scRepository.findByCname(cname);
    }

    public SC insert(SC sc){
        return scRepository.save(sc);
    }

    public SC update(SC sc){

        return scRepository.save(sc);
    }

    public void delete(Integer id){
        SC sc = new SC();
        sc.setId(id);
        scRepository.delete(sc);
    }

    public void delete(Integer[] arr){
        SC sc = new SC();
        for (int i = 0;i < arr.length;i++){
            sc.setId(arr[i]);
            scRepository.delete(sc);
        }
    }

    @Override
    public int insertSC(MultipartFile file) throws Exception {
        int result = 0;
        //存放excel表中所有数据
        List<SC> eaxmList = new ArrayList<>();

        //file.getOriginalFilename()方法 得到上传时的文件名
        String fileName = file.getOriginalFilename();
        //截取文件名的后缀
        String suffix = fileName.substring(fileName.lastIndexOf(".")+1);

        //file.getInputStream()方法  返回InputStream对象 读取文件的内容
        InputStream ins = file.getInputStream();
        Workbook wb = null;
        /*判断文件后缀
            XSSF － 提供读写Microsoft Excel OOXML XLSX格式档案的功能。
            HSSF － 提供读写Microsoft Excel XLS格式档案的功能。*/
        if(suffix.equals("xlsx")){
            wb = new XSSFWorkbook(ins);
        }else{
            wb = new HSSFWorkbook(ins);
        }

        //获取excel表单的sheet对象
        Sheet sheet = wb.getSheetAt(0);
        //如果sheet不为空，就开始遍历表中的数据
        if(null != sheet){
            //line = 1 :从表的第2行开始获取记录
            for(int line = 1; line <= sheet.getLastRowNum();line++){

                //excel表单的sheet的行对象
                Row row = sheet.getRow(line);

                //如果某行为空，跳出本行
                if(null == row){
                    continue;
                }
                //获取第一个单元格的内容
                //表示获取单元格中的内容是String字符串类型
                row.getCell(0).setCellType(CellType.STRING);
                row.getCell(1).setCellType(CellType.STRING);
                row.getCell(2).setCellType(CellType.STRING);
                row.getCell(3).setCellType(CellType.STRING);

                String sno = row.getCell(0).getStringCellValue();
                String sname = row.getCell(1).getStringCellValue();
                String cno = row.getCell(2).getStringCellValue();
                String cname = row.getCell(3).getStringCellValue();
                //这解决的是单元格内读取的日期是天（写的是年月日，但是读取后变成了总天数），需要休眠操作在转换成年月日格式
//                Calendar calendar = new GregorianCalendar(1900,0,-1);
//                Date d = calendar.getTime();
//                Date examtime = DateUtils.addDays(d,Integer.valueOf(examti);
//                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
//                String timeFormat = sdf.format(examtime);


                //获取第二个单元格的内容
                //格式是number
//                Integer sage = Integer.valueOf(row.getCell(3).getStringCellValue());
//
//                Integer classid = Integer.valueOf(row.getCell(4).getStringCellValue());
//                Integer gradeid = Integer.valueOf(row.getCell(5).getStringCellValue());
                Double score1 = row.getCell(4).getNumericCellValue();
                int score = new Double(score1).intValue();



                SC eaxm = new SC();

                eaxm.setSno(sno);
                eaxm.setSname(sname);
                eaxm.setCno(cno);
                eaxm.setCname(cname);
                eaxm.setScore(score);


                eaxmList.add(eaxm);

            }
//            //这其实可以在做一下 判断  是否数据库里已经存在了你要导入数据，我么得写，不想写，懒，难受
            for(SC eaxm:eaxmList){

//                List<Student> students = studentRepository.findBySnameLike(eaxm.getSname());
//                if (students.size() == 0){
//                    result = studentMapper.addExcelStudent(eaxm);
                SC sc = new SC();
                sc.setSno(eaxm.getSno());
                sc.setSname(eaxm.getSname());
                sc.setCno(eaxm.getCno());
                sc.setCname(eaxm.getCname());
                sc.setScore(eaxm.getScore());

                scRepository.save(sc);
                if(sc != null){
                    result = 1;
                }
//                    System.out.println(result);
//                }

            }
        }
        return result;
    }


    /**
     * excel导出学生表
     * @param response
     */
    public void exportSC(HttpServletResponse response){
        try {
            //从数据库查询到数据
            List<SC> scs = scRepository.findAll();

            //设置信息头，告诉浏览器内容为excel类型
            response.setHeader("content-Type", "application/vnd.ms-excel");
            //设置下载名称
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("选课信息表.xls", StandardCharsets.UTF_8.name()));
            //字节流输出
            ServletOutputStream out = response.getOutputStream();
            //设置excel参数
            ExportParams params = new ExportParams();
            //设置sheet名
            params.setSheetName("选课列表");
            //设置标题
            params.setTitle("选课信息表");

            //转成对应的类型;要不然会报错，虽然也可以导出成功。
            List<importSC> exportUsers = changeType(scs);
            //导入excel
            Workbook workbook = ExcelExportUtil.exportExcel(params, importSC.class,exportUsers );
            //写入
            workbook.write(out);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 转成导出vo
     *
     * @param users  users集合
     */
    private List<importSC> changeType(List<SC> users) {
        List<importSC> res = new ArrayList<>();
        for (SC user : users) {
            importSC exportUser = new importSC(user);
            res.add(exportUser);
        }
        return res;
    }
}
